package service

import (
	"duoke/model"
	"duoke/tables"
	"duoke/utils/gmd5"
	"duoke/utils/orm"
	"errors"
	"github.com/gin-gonic/gin"
)

var GoodsUser = new(goodsUserService)

type goodsUserService struct{}

// 账户登录
func (s *goodsUserService) Create(c *gin.Context, goodsId int, fromId int) (*tables.GoodsUser, error) {
	accountR, _ := Request.Account(c)
	userR, _ := Request.User(c)
	if userR.Id == 0 || accountR.Id == 0 {
		return nil, nil
	}
	user, err := User.GetById(c, userR.Id, "")
	if err != nil {
		return nil, err
	}
	goodsUser := new(tables.GoodsUser)
	has, err := orm.Db.Where("acid  =? AND goods_id =? AND user_id=?", accountR.Id, goodsId, user.Id).Get(goodsUser)
	if err != nil {
		return nil, err
	}
	if has {
		if goodsUser.Nickname == "" || goodsUser.Avatar == "" {
			goodsUser.Nickname = user.Nickname
			goodsUser.Avatar = user.Avatar
			_, err = orm.Db.ID(goodsUser.Id).Cols("nickname", "avatar").Update(goodsUser)
			if err != nil {
				return nil, err
			}
		}
		return goodsUser, nil
	}
	goodsUser.Acid = accountR.Id
	goodsUser.GoodsId = goodsId
	goodsUser.UserId = user.Id
	goodsUser.Openid = user.Openid
	goodsUser.Nickname = user.Nickname
	goodsUser.Avatar = user.Avatar
	// 推荐人信息
	fromGoodsUser, _ := s.GetByGoodsUserId(c, goodsId, fromId, "")
	if fromGoodsUser != nil {
		goodsUser.FromId = fromGoodsUser.UserId
		goodsUser.FromId2 = fromGoodsUser.FromId
		goodsUser.StaffId = fromGoodsUser.StaffId
	}
	affected, err := orm.Db.Insert(goodsUser)
	if err != nil {
		return nil, err
	}
	if affected == 0 {
		return nil, errors.New("创建商品用户失败")
	}
	return goodsUser, nil
}

// 获取用户信息
func (s *goodsUserService) GetByGoodsUserId(c *gin.Context, goodsId int, userId int, field string) (*tables.GoodsUser, error) {
	accountR, _ := Request.Account(c)
	data := new(tables.GoodsUser)
	has, err := orm.Db.Where("acid =? AND goods_id =? AND user_id =?", accountR.Id, goodsId, userId).Cols(field).Get(data)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, errors.New("商品用户不存在")
	}
	return data, nil
}

// 获取用户信息
func (s *goodsUserService) GetById(c *gin.Context, goodsId int, userId int, field string) *tables.GoodsUser {
	accountR, _ := Request.Account(c)
	if goodsId == 0 || userId == 0 {
		return nil
	}
	data := new(tables.GoodsUser)
	has, err := orm.Db.Where("acid =? AND goods_id =? AND user_id =?", accountR.Id, goodsId, userId).Cols(field).Get(data)
	if err != nil {
		return nil
	}
	if !has {
		return nil
	}
	return data
}

// 分页列表
func (s *goodsUserService) Page(c *gin.Context, req model.ReqList) ([]model.GoodsUserList, int64, error) {
	accountR, _ := Request.Account(c)
	// 分页
	offset := (req.PageNo - 1) * req.PageSize
	list := make([]model.GoodsUserList, 0)
	query := orm.Db.Desc("id")
	//判断子账户
	if accountR.Role == "goods" {
		query = query.Where("goods_id IN(" + accountR.GoodsIds + ")")
	} else {
		query = query.Where("acid =?", accountR.Id)
	}
	if req.Keyword != "" {
		query = query.Where("(nickname =? OR user_id =?)", req.Keyword, req.Keyword)
	}
	if req.GoodsId != "" {
		query = query.Where("goods_id =?", req.GoodsId)
	}
	if req.IsStaff != "" {
		query = query.Where("is_staff =?", 1)
	}
	if req.IsVerifier != "" {
		query = query.Where("is_verifier =?", 1)
	}
	if req.IsRobot != "" {
		query = query.Where("is_robot =?", 1)
	}
	if req.FromId != "" {
		query = query.Where("from_id =?", req.FromId)
	}
	if req.StaffId != "" {
		query = query.Where("staff_id =?", req.StaffId)
	}
	total, err := query.Limit(req.PageSize, offset).FindAndCount(&list)
	if err != nil {
		return nil, 0, err
	}
	for i, v := range list {
		orderList := make([]tables.Order, 0)
		orm.Db.Desc("id").Where("from_id =? AND goods_id =? AND pay_state =?", v.UserId, req.GoodsId, 1).Find(&orderList)
		list[i].OrderNum = len(orderList)
		list[i].OrderList = orderList
	}
	return list, total, nil
}
func (s *goodsUserService) Set(id int, atype string) (bool, error) {
	user := new(tables.GoodsUser)
	has, err := orm.Db.ID(id).Get(user)
	if err != nil {
		return false, err
	}
	if !has {
		return false, errors.New("用户不存在")
	}
	if atype == "staff" {
		if user.IsStaff == 1 {
			user.IsStaff = 0
			user.StaffId = 0
		} else {
			user.IsStaff = 1
			user.Password = gmd5.MustEncrypt("888888")
			user.StaffId = user.UserId
		}
	}
	if atype == "verifier" {
		if user.IsVerifier == 1 {
			user.IsVerifier = 0
		} else {
			user.IsVerifier = 1
		}
	}
	_, err = orm.Db.ID(id).Cols("is_staff", "staff_id", "is_verifier", "Password").Update(user)
	if err != nil {
		return false, err
	}
	return true, nil
}

// 删除用户
func (s *goodsUserService) Del(c *gin.Context, req model.ReqId) error {
	accountR, _ := Request.Account(c)
	_, err := orm.Db.ID(req.Id).Where("acid =?", accountR.Id).Delete(new(tables.GoodsUser))
	if err != nil {
		return err
	}
	return nil
}

// 账户保存
func (s *goodsUserService) UpdateInfo(c *gin.Context, req model.ReqUser) error {
	accountR, _ := Request.Account(c)
	userR, _ := Request.User(c)
	user := new(tables.GoodsUser)
	user.Nickname = req.Nickname
	user.Avatar = req.Avatar
	user.Name = req.Name
	user.Phone = req.Phone
	_, err := orm.Db.Where("acid =? AND user_id =?", accountR.Id, userR.Id).Update(user)
	return err
}
